﻿using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;
using ZBJF.Warranty.Model.ViewModel.PageActionManager;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Areas.System.Controllers
{
    public class RoleController : BaseController
    {
        public ActionResult Index()
        {
            ViewBag.Title = "角色列表";
            return View();
        }

        [HttpPost]
        public JsonResult Index(BaseQueryParams model)
        {
            int rowCount = 0;
            var result = ServiceFactory.SystemRoleServiceInstance.GetPagingList(model, out rowCount).Select(o => new
            {
                o.ID,
                o.Intro,
                o.IsAvailable,
                o.OrderIndex,
                o.RoleName,
                o.RoleCode,
                o.RoleNameEN,
                o.RoleNameRU,
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
        [HttpPost]
        public JsonResult GetRoleToPageToAction(RoleToPageToActionModel model)
        {
            int rowCount = 0;
            var result = ServiceFactory.RoleToPageToActionServiceInstance.GetPagingList(model, out rowCount).Include(o => o.PageToAction).Include(o => o.PageToAction.PageMenu).Include(o => o.PageToAction.PageAction).OrderBy(o => o.PageToAction.PageMenu.BelongApplicationType).ThenBy(o => o.PageToAction.PageMenu.ParentID).ThenBy(o => o.PageToAction.PageMenu.OrderIndex).AsNoTracking().ToList().Select(o => new
            {
                o.ID,
                o.PageToAction.ActionID,
                PageName = ServiceFactory.PageMenuServiceInstance.GetFullPageMenuName(o.PageToAction.PageMenu.ID),
                o.PageToAction.PageMenu.BelongApplicationType,
                BelongApplicationTypeDesc = EnumHelper.Instance.GetDescription(typeof(ApplicationType), o.PageToAction.PageMenu.BelongApplicationType),
                o.PageToAction.PageMenu.PageUrl,
                o.PageToAction.PageAction.ActionName,
                o.PageToAction.PageAction.ActionCode,
            });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Edit(int id)
        {
            var role = ServiceFactory.SystemRoleServiceInstance.LoadByID(id);
            return View(role);
        }
        public ActionResult RoleToPageAcionMapping(int roleId)
        {
            var role = ServiceFactory.RoleToPageToActionServiceInstance.LoadEntities(o => o.RoleID == roleId).ToList();
            return View(role);
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(Model.SystemRole model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            if (ModelState.IsValid)
            {
                if (model.ID > 0)
                {
                    if (ServiceFactory.SystemRoleServiceInstance.IsExistRoleName(model.RoleName, model.ID))
                    {
                        responseResult.Message = "角色名称已经存在其他角色中";
                    }
                    else if (ServiceFactory.SystemRoleServiceInstance.IsExistRoleCode(model.RoleCode, model.ID))
                    {
                        responseResult.Message = "角色代码已经存在其他角色中";
                    }
                    else
                    {
                        var entity = ServiceFactory.SystemRoleServiceInstance.LoadByID(model.ID);
                        if (entity != null)
                        {
                            entity.Intro = model.Intro;
                            entity.IsAvailable = model.IsAvailable;
                            entity.OrderIndex = model.OrderIndex;
                            entity.RoleName = model.RoleName;
                            entity.RoleNameEN = model.RoleNameEN;
                            entity.RoleNameRU = model.RoleNameRU;
                            entity.RoleCode = model.RoleCode;
                            responseResult.Success = ServiceFactory.SystemRoleServiceInstance.UpdateEntities(entity);
                        }
                        else
                        {
                            responseResult.Message = "该角色已不存在!";
                        }
                    }
                }
                else
                {
                    if (!ServiceFactory.SystemRoleServiceInstance.IsExistRoleName(model.RoleName))
                    {
                        if (!ServiceFactory.SystemRoleServiceInstance.IsExistRoleCode(model.RoleCode))
                        {
                            responseResult.Success = ServiceFactory.SystemRoleServiceInstance.AddEntities(model).ID > 0;
                        }
                        else
                        {
                            responseResult.Message = "角色代码已经存在了";
                        }
                    }
                    else
                    {
                        responseResult.Message = "角色名称已经存在了";
                    }
                }
            }
            else
            {
                responseResult.Message = "信息不完整！";
            }
            if (responseResult.Success)
            {
                CacheHelper.Instance.RemoveAllCache();
            }
            TempData["responseResult"] = responseResult;
            return RedirectToAction("Edit", new { id = model.ID });
        }
        /// <summary>
        /// 更改角色状态
        /// </summary>
        /// <param name="id">角色Id</param>
        /// <param name="isAvailable">角色状态</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id = 0, bool isAvailable = false)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var result = ServiceFactory.SystemRoleServiceInstance.LoadByID(id);
            if (result != null)
            {
                result.IsAvailable = isAvailable;
                responseResult.Success = ServiceFactory.SystemRoleServiceInstance.UpdateEntities(result);
                CacheHelper.Instance.RemoveAllCache();
            }
            else
            {
                responseResult.Message = "该角色已不存在！";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="id">角色Id</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteRole(int id = 0)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Delete
            };
            var result = ServiceFactory.SystemRoleServiceInstance.LoadByID(id);
            if (result != null)
            {
                responseResult.Success = ServiceFactory.SystemRoleServiceInstance.DeleteEntities(result);
                CacheHelper.Instance.RemoveAllCache();
            }
            else
            {
                responseResult.Message = "该角色已不存在";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }

        [HttpPost]
        public ActionResult UpdateRoleToPageToAction(int roleID, List<PageToActionModel> model)
        {
            var addCount = 0;
            if (roleID > 0)
            {
                // ReSharper disable once LoopCanBeConvertedToQuery
                foreach (var entity in model)
                {
                    if (entity.Checked)
                    {
                        var roleToPageToAction = new RoleToPageToAction
                        {
                            RoleID = roleID,
                            PageToActionID = entity.ID
                        };

                        var isExsitEntity = ServiceFactory.RoleToPageToActionServiceInstance.LoadEntities(
                               p => p.RoleID == roleToPageToAction.RoleID &&
                                   p.PageToActionID == roleToPageToAction.PageToActionID);
                        if (!isExsitEntity.Any())
                        {
                            addCount += (ServiceFactory.RoleToPageToActionServiceInstance.AddEntities(roleToPageToAction).ID > 0 ? 1 : 0);
                        }
                    }
                }
            }
            var responseResult = new ResponseResult
            {
                Success = true,
                Message = string.Format("添加{0}个", addCount)
            };
            TempData["responseResult"] = responseResult;
            return RedirectToAction("RoleToPageAcionMapping", new { RoleID = roleID });
        }
        /// <summary>
        /// 删除权限
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult DeleteRoleToPageToAction(int id = 0)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Delete
            };
            var result = ServiceFactory.RoleToPageToActionServiceInstance.LoadEntities(o => o.ID == id).FirstOrDefault();
            if (result != null)
            {
                responseResult.Success = ServiceFactory.RoleToPageToActionServiceInstance.DeleteEntities(result);
                CacheHelper.Instance.RemoveAllCache();
            }
            else
            {
                responseResult.Message = "该权限已不存在";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
    }
}
